{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Copyright (c) MONAI Consortium  \n",
    "Licensed under the Apache License, Version 2.0 (the \"License\");  \n",
    "you may not use this file except in compliance with the License.  \n",
    "You may obtain a copy of the License at  \n",
    "&nbsp;&nbsp;&nbsp;&nbsp;http://www.apache.org/licenses/LICENSE-2.0  \n",
    "Unless required by applicable law or agreed to in writing, software  \n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,  \n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  \n",
    "See the License for the specific language governing permissions and  \n",
    "limitations under the License. \n",
    "\n",
    "# Customize Data Analysis in Auto3DSeg\n",
    "\n",
    "In this notebook, we will provide a brief example of how to to customize your data analysis pipeline by writing new operations on new metadata."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setup environment"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "!python -c \"import monai\" || pip install -q \"monai-weekly[nibabel]\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setup imports"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import torch\n",
    "import tempfile\n",
    "import nibabel as nib\n",
    "import numpy as np\n",
    "\n",
    "from copy import deepcopy\n",
    "from tqdm import tqdm\n",
    "\n",
    "from monai.auto3dseg.analyzer import Analyzer\n",
    "from monai.auto3dseg import (\n",
    "    SampleOperations,\n",
    "    SegSummarizer,\n",
    "    concat_val_to_np,\n",
    "    datafold_read,\n",
    ")\n",
    "from monai.config import print_config\n",
    "from monai.data import DataLoader, Dataset, create_test_image_3d\n",
    "from monai.data.utils import no_collation\n",
    "from monai.transforms import (\n",
    "    Compose,\n",
    "    EnsureChannelFirstd,\n",
    "    EnsureTyped,\n",
    "    Lambdad,\n",
    "    LoadImaged,\n",
    "    Orientationd,\n",
    "    SqueezeDimd,\n",
    "    ToDeviced,\n",
    ")\n",
    "\n",
    "from monai.utils.enums import DataStatsKeys\n",
    "\n",
    "\n",
    "def _argmax_if_multichannel(x):\n",
    "    return torch.argmax(x, dim=0, keepdim=True) if x.shape[0] > 1 else x\n",
    "\n",
    "\n",
    "print_config()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Simulate a dataset and Auto3D datalist using MONAI functions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "data are generated and saved in this directory:  /var/folders/6f/fdkl7m0x7sz3nj_t7p3ccgz00000gp/T/tmpk7ystn9f\n"
     ]
    }
   ],
   "source": [
    "sim_datalist = {\n",
    "    \"testing\": [\n",
    "        {\"image\": \"val_001.fake.nii.gz\"},\n",
    "        {\"image\": \"val_002.fake.nii.gz\"},\n",
    "        {\"image\": \"val_003.fake.nii.gz\"},\n",
    "        {\"image\": \"val_004.fake.nii.gz\"},\n",
    "        {\"image\": \"val_005.fake.nii.gz\"},\n",
    "    ],\n",
    "    \"training\": [\n",
    "        {\"fold\": 0, \"image\": \"tr_image_001.fake.nii.gz\", \"label\": \"tr_label_001.fake.nii.gz\"},\n",
    "        {\"fold\": 0, \"image\": \"tr_image_002.fake.nii.gz\", \"label\": \"tr_label_002.fake.nii.gz\"},\n",
    "        {\"fold\": 0, \"image\": \"tr_image_003.fake.nii.gz\", \"label\": \"tr_label_003.fake.nii.gz\"},\n",
    "        {\"fold\": 0, \"image\": \"tr_image_004.fake.nii.gz\", \"label\": \"tr_label_004.fake.nii.gz\"},\n",
    "        {\"fold\": 0, \"image\": \"tr_image_005.fake.nii.gz\", \"label\": \"tr_label_005.fake.nii.gz\"},\n",
    "        {\"fold\": 0, \"image\": \"tr_image_006.fake.nii.gz\", \"label\": \"tr_label_006.fake.nii.gz\"},\n",
    "        {\"fold\": 0, \"image\": \"tr_image_007.fake.nii.gz\", \"label\": \"tr_label_007.fake.nii.gz\"},\n",
    "        {\"fold\": 0, \"image\": \"tr_image_008.fake.nii.gz\", \"label\": \"tr_label_008.fake.nii.gz\"},\n",
    "        {\"fold\": 0, \"image\": \"tr_image_009.fake.nii.gz\", \"label\": \"tr_label_009.fake.nii.gz\"},\n",
    "        {\"fold\": 0, \"image\": \"tr_image_010.fake.nii.gz\", \"label\": \"tr_label_010.fake.nii.gz\"},\n",
    "        {\"fold\": 1, \"image\": \"tr_image_006.fake.nii.gz\", \"label\": \"tr_label_006.fake.nii.gz\"},\n",
    "        {\"fold\": 1, \"image\": \"tr_image_007.fake.nii.gz\", \"label\": \"tr_label_007.fake.nii.gz\"},\n",
    "        {\"fold\": 1, \"image\": \"tr_image_008.fake.nii.gz\", \"label\": \"tr_label_008.fake.nii.gz\"},\n",
    "        {\"fold\": 1, \"image\": \"tr_image_009.fake.nii.gz\", \"label\": \"tr_label_009.fake.nii.gz\"},\n",
    "        {\"fold\": 1, \"image\": \"tr_image_010.fake.nii.gz\", \"label\": \"tr_label_010.fake.nii.gz\"},\n",
    "        {\"fold\": 1, \"image\": \"tr_image_011.fake.nii.gz\", \"label\": \"tr_label_011.fake.nii.gz\"},\n",
    "        {\"fold\": 1, \"image\": \"tr_image_012.fake.nii.gz\", \"label\": \"tr_label_012.fake.nii.gz\"},\n",
    "        {\"fold\": 1, \"image\": \"tr_image_013.fake.nii.gz\", \"label\": \"tr_label_013.fake.nii.gz\"},\n",
    "        {\"fold\": 1, \"image\": \"tr_image_014.fake.nii.gz\", \"label\": \"tr_label_014.fake.nii.gz\"},\n",
    "        {\"fold\": 1, \"image\": \"tr_image_015.fake.nii.gz\", \"label\": \"tr_label_015.fake.nii.gz\"},\n",
    "    ],\n",
    "}\n",
    "\n",
    "\n",
    "def simulate():\n",
    "    test_dir = tempfile.TemporaryDirectory()\n",
    "    dataroot = test_dir.name\n",
    "\n",
    "    # Generate a fake dataset\n",
    "    for d in sim_datalist[\"testing\"] + sim_datalist[\"training\"]:\n",
    "        im, seg = create_test_image_3d(39, 47, 46, rad_max=10)\n",
    "        nib_image = nib.Nifti1Image(im, affine=np.eye(4))\n",
    "        image_fpath = os.path.join(dataroot, d[\"image\"])\n",
    "        nib.save(nib_image, image_fpath)\n",
    "\n",
    "        if \"label\" in d:\n",
    "            nib_image = nib.Nifti1Image(seg, affine=np.eye(4))\n",
    "            label_fpath = os.path.join(dataroot, d[\"label\"])\n",
    "            nib.save(nib_image, label_fpath)\n",
    "\n",
    "    return dataroot, test_dir\n",
    "\n",
    "\n",
    "sim_dataroot, test_dir = simulate()\n",
    "print(\"data are generated and saved in this directory: \", sim_dataroot)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Perform analysis on a different image meta data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "class DimsAnalyzer(Analyzer):\n",
    "    def __init__(self, image_key=\"image\", stats_name=\"user_stats\"):\n",
    "        self.image_key = image_key\n",
    "        report_format = {\"ndims\": None}\n",
    "        super().__init__(stats_name, report_format)\n",
    "\n",
    "    def __call__(self, data):\n",
    "        d = dict(data)\n",
    "        report = deepcopy(self.get_report_format())\n",
    "        report[\"ndims\"] = d[self.image_key].ndim\n",
    "        d[self.stats_name] = report\n",
    "        return d\n",
    "\n",
    "\n",
    "class DimsSummaryAnalyzer(Analyzer):\n",
    "    def __init__(self, stats_name=\"user_stats\"):\n",
    "        report_format = {\"ndims\": None}\n",
    "        super().__init__(stats_name, report_format)\n",
    "        self.update_ops(\"ndims\", SampleOperations())\n",
    "\n",
    "    def __call__(self, data):\n",
    "        report = deepcopy(self.get_report_format())\n",
    "        v_np = concat_val_to_np(data, [self.stats_name, \"ndims\"])\n",
    "        report[\"ndims\"] = self.ops[\"ndims\"].evaluate(v_np)\n",
    "        return report\n",
    "\n",
    "\n",
    "# it has the three default analyzers (ImageStats, FgImageStats, LabelStats)\n",
    "summarizer = SegSummarizer(\"image\", \"label\")\n",
    "summarizer.add_analyzer(DimsAnalyzer(), DimsSummaryAnalyzer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "monai.transforms.io.dictionary LoadImaged.__init__:image_only: Current default value of argument `image_only=False` has been deprecated since version 1.1. It will be changed to `image_only=True` in version 1.3.\n",
      "100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 20/20 [00:00<00:00, 30.77it/s]\n"
     ]
    }
   ],
   "source": [
    "def my_analyzer(datalist, dataroot, my_summarizer):\n",
    "    keys = [\"image\", \"label\"]\n",
    "    transform_list = [\n",
    "        LoadImaged(keys=keys),\n",
    "        EnsureChannelFirstd(keys=keys),  # this creates label to be (1,H,W,D)\n",
    "        Orientationd(keys=keys, axcodes=\"RAS\"),\n",
    "        EnsureTyped(keys=keys, data_type=\"tensor\"),\n",
    "        Lambdad(keys=\"label\", func=_argmax_if_multichannel),\n",
    "        SqueezeDimd(keys=[\"label\"], dim=0),\n",
    "        ToDeviced(keys=keys, device=\"cuda\" if torch.cuda.is_available() else \"cpu\"),\n",
    "        my_summarizer,\n",
    "    ]\n",
    "\n",
    "    transform = Compose(transforms=list(filter(None, transform_list)))\n",
    "\n",
    "    files, _ = datafold_read(datalist=datalist, basedir=dataroot, fold=-1)\n",
    "    dataset = Dataset(data=files, transform=transform)\n",
    "    dataloader = DataLoader(dataset, batch_size=1, shuffle=False, num_workers=0, collate_fn=no_collation)\n",
    "    result = {DataStatsKeys.SUMMARY: {}, DataStatsKeys.BY_CASE: []}\n",
    "\n",
    "    for batch_data in tqdm(dataloader):\n",
    "        d = batch_data[0]\n",
    "        stats_by_cases = {\n",
    "            DataStatsKeys.BY_CASE_IMAGE_PATH: d[DataStatsKeys.BY_CASE_IMAGE_PATH],\n",
    "            DataStatsKeys.BY_CASE_LABEL_PATH: d[DataStatsKeys.BY_CASE_LABEL_PATH],\n",
    "            DataStatsKeys.IMAGE_STATS: d[DataStatsKeys.IMAGE_STATS],\n",
    "            DataStatsKeys.FG_IMAGE_STATS: d[DataStatsKeys.FG_IMAGE_STATS],\n",
    "            DataStatsKeys.LABEL_STATS: d[DataStatsKeys.LABEL_STATS],\n",
    "            DataStatsKeys.IMAGE_HISTOGRAM: d[DataStatsKeys.IMAGE_HISTOGRAM],\n",
    "            \"user_stats\": d[\"user_stats\"],\n",
    "        }\n",
    "\n",
    "    result[DataStatsKeys.BY_CASE].append(stats_by_cases)\n",
    "    result[DataStatsKeys.SUMMARY] = my_summarizer.summarize(result[DataStatsKeys.BY_CASE])\n",
    "    return result\n",
    "\n",
    "\n",
    "result = my_analyzer(sim_datalist, sim_dataroot, summarizer)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'ndims': 4}\n"
     ]
    }
   ],
   "source": [
    "print(result[DataStatsKeys.BY_CASE][0][\"user_stats\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'ndims': {'max': 4, 'mean': 4.0, 'median': 4.0, 'min': 4, 'stdev': 0.0, 'percentile': [4, 4, 4, 4], 'percentile_00_5': 4, 'percentile_10_0': 4, 'percentile_90_0': 4, 'percentile_99_5': 4}}\n"
     ]
    }
   ],
   "source": [
    "print(result[DataStatsKeys.SUMMARY][\"user_stats\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Add a new stat operation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 20/20 [00:00<00:00, 30.27it/s]\n"
     ]
    }
   ],
   "source": [
    "op = SampleOperations()\n",
    "# add a new operation\n",
    "op.update({\"sum\": np.sum})\n",
    "\n",
    "\n",
    "class NewDimsSummaryAnalyzer(Analyzer):\n",
    "    def __init__(self, stats_name=\"user_stats\"):\n",
    "        report_format = {\"ndims\": None}\n",
    "        super().__init__(stats_name, report_format)\n",
    "        self.update_ops(\"ndims\", op)\n",
    "\n",
    "    def __call__(self, data):\n",
    "        report = deepcopy(self.get_report_format())\n",
    "        v_np = concat_val_to_np(data, [self.stats_name, \"ndims\"])\n",
    "        report[\"ndims\"] = self.ops[\"ndims\"].evaluate(v_np)\n",
    "        return report\n",
    "\n",
    "\n",
    "summarizer = SegSummarizer(\"image\", \"label\")\n",
    "summarizer.add_analyzer(DimsAnalyzer(), NewDimsSummaryAnalyzer())\n",
    "result = my_analyzer(sim_datalist, sim_dataroot, summarizer)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'ndims': {'max': 4, 'mean': 4.0, 'median': 4.0, 'min': 4, 'stdev': 0.0, 'percentile': [4, 4, 4, 4], 'sum': 4, 'percentile_00_5': 4, 'percentile_10_0': 4, 'percentile_90_0': 4, 'percentile_99_5': 4}}\n"
     ]
    }
   ],
   "source": [
    "print(result[DataStatsKeys.SUMMARY][\"user_stats\"])"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.13"
  },
  "vscode": {
   "interpreter": {
    "hash": "d4d1e4263499bec80672ea0156c357c1ee493ec2b1c70f0acce89fc37c4a6abe"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
